package com.bj58.data.hadoop.info.dimension;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;



public class DimensionParser {

	public static List<IDimension> loadOneConfig(String configStr) throws InstantiationException, IllegalAccessException,ClassNotFoundException {

		List<IDimension> dimList = new ArrayList<IDimension>();
		try {
			String[] dimensionStr = configStr.split("###");
			for (String dim : dimensionStr) {
				String[] keyValue = dim.split(":");
				IDimension dimTemp = DimensionFactory.createDimension(keyValue[0]);
				dimTemp.setCareValues(keyValue[1]);
				dimList.add(dimTemp);
			}
			DimensionComparator comparator = new DimensionComparator();
			Collections.sort(dimList, comparator);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(configStr);
		}
		
		return dimList;
	}

	public static List<List<IDimension>> readConfig(String configName) throws Exception {
		InputStream ins = DimensionParser.class.getClassLoader().getResourceAsStream(configName);
		InputStreamReader inr = new InputStreamReader(ins);
		List<List<IDimension>> allCareList = new ArrayList<List<IDimension>>();
		BufferedReader br = new BufferedReader(inr);
		String temp = "";
		String statID = "";
		Map<String, String> statMap = new HashMap<String, String>();
		Map<String, String> contentMap = new HashMap<String, String>();
		while ((temp = br.readLine()) != null) {
			if (temp.startsWith("stat_list")) {
				for (String stat : temp.split(":")[1].split(",")) {
					statMap.put(stat, "1");
				}
				continue;
			}
			if (temp.startsWith("stat_id")) {
				statID = temp.split(":")[1];
				contentMap.put(statID, "");
			} 
			else if (!temp.equals("")) {
				contentMap.put(statID, temp);
			}
		}
	
		Map<String,String> filerMap = new HashMap<String,String>();
		
		Iterator<Entry<String, String>> it = contentMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> itTemp = it.next();
			List<IDimension> oneDimList = DimensionParser.loadOneConfig(itTemp.getValue());
			String rowKeyPreFix = "";
			for(IDimension dim:oneDimList)
			{
				rowKeyPreFix += dim.getRowKeyPrefix()+"_";
			}
			if(filerMap.containsKey(rowKeyPreFix))
			{
				System.out.println(itTemp.getValue()+" 重复:"+filerMap.get(rowKeyPreFix));
				continue;
			}
			else
			{
				filerMap.put(rowKeyPreFix, itTemp.getValue());
				allCareList.add(oneDimList);
			}
		}
		System.out.println("规则数量:"+allCareList.size());
		return allCareList;
	}
	
	public static void main(String[] args) throws Exception {
		DimensionParser.readConfig("stat_config.conf");
	}
}
